package com.wframe.project.jnd.controller;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.wframe.project.jnd.rest.util.ClientException;
import com.wframe.project.jnd.rest.util.CodeEnum;
import com.wframe.project.jnd.wx.constant.Constant;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import com.frame.database.JdataBean;
import com.frame.database.PageResult;
import com.wframe.project.jnd.rest.util.JsonReturn;
import com.wframe.project.jnd.rest.util.WebSession;
import com.wframe.project.jnd.services.CouponService;
import com.wframe.project.jnd.services.UserService;
import com.wframe.project.jnd.util.WebUtils;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping("/coupon")
public class CouponController {

    @Autowired
    CouponService couponService;
    @Autowired
    UserService userService;

    @RequestMapping(value = "show")
    public String show(HttpServletRequest request, Model model) throws Exception {
        if (!WebSession.checkLoginStatus(request.getSession())) {
            return "redirect:/user/showlogin";
        }
        PageResult pr = couponService.queryCoupon(WebSession.getWbUser(request.getSession()).getUserid(), 1, UserService.UserSourceEnum.PC.ordinal(), 1, 1);
        model.addAttribute("count", pr.getResultCount());
        model.addAttribute("user", userService.getUser(WebSession.getWbUser(request.getSession()).getUserid()).getDataMap());
        return "/website/user/coupon";
    }

    @RequestMapping(value = "list")
    public String list(Integer state, String psize, String pno, HttpServletRequest request, Model model) throws Exception {
        if (!WebSession.checkLoginStatus(request.getSession())) {
            return "redirect:/user/showlogin";
        }
        int pagesize = 6;
        int pageno = 1;
        if (StringUtils.isNotBlank(psize)) {
            pagesize = Integer.parseInt(psize);
        }
        if (StringUtils.isNotBlank(pno)) {
            pageno = Integer.parseInt(pno);
        }
        PageResult pr = couponService.queryCoupon(WebSession.getWbUser(request.getSession()).getUserid(), state, UserService.UserSourceEnum.PC.ordinal(), pagesize, pageno);
        List<Map> list = pr.getList();
        for (Map map : list) {
            map.put("state", state);
        }
        model.addAttribute("list", list);
        model.addAttribute("pageCount",pr.getPageCount());
        model.addAttribute("pagehtml", WebUtils.toPageHtml(pr, 7));
        return "/website/user/couponList";
    }

    /**
     * 领取优惠券
     *
     * @param couponId
     * @param session
     * @return
     * @throws ClientException
     */
    @RequestMapping(value = "/receive/{id}", method = RequestMethod.POST)
    @ResponseBody
    public String addCoupon(@PathVariable("id") Integer couponId, HttpSession session) throws ClientException {
        JsonReturn json = new JsonReturn();
        String userId = WebSession.getUserId(session);
        JdataBean coupon = couponService.findOne(userId, couponId, UserService.UserSourceEnum.PC.ordinal());
        if (coupon != null) {
            json.putData(coupon.getInt("amount") > (coupon.getInt("sales") + 1) && coupon.getInt("limit_num") > (coupon.getInt("num") + 1));
            couponService.receiveCoupon(coupon, userId, Constant.COUPON_SOURCE_ACQUIRE);
        } else {
            throw new ClientException(CodeEnum.ILLEGAL_COUPON);
        }

        return json.toString();
    }

    /**
     * 可领取的优惠券
     *
     * @param session
     * @return
     * @throws ClientException
     */
    @RequestMapping(value = "/avail", method = RequestMethod.GET)
    @ResponseBody
    public String available(HttpSession session) throws ClientException {
        JsonReturn json = new JsonReturn();
        json.putData(couponService.findAvailableCoupons(WebSession.getUserId(session), UserService.UserSourceEnum.PC.ordinal()));
        return json.toString();
    }

    /**
     * 我的优惠券
     *
     * @param session
     * @return
     * @throws ClientException
     */
    @RequestMapping(method = RequestMethod.GET)
    @ResponseBody
    public String list(HttpSession session) throws ClientException {
        JsonReturn json = new JsonReturn();
        json.putData(couponService.findReceivedCoupons(WebSession.getUserId(session), UserService.UserSourceEnum.PC.ordinal()));
        return json.toString();
    }

    /**
     * 加载可用优惠劵
     *
     * @param psize
     * @param pno
     * @param response
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "loadcanlist")
    public void loadcanlist(Double ordermoney, String psize, String pno, HttpSession session, HttpServletResponse response) throws Exception {
        JsonReturn json = new JsonReturn();
        try {
            int pagesize = 10;
            int pageno = 1;
            if (StringUtils.isNotBlank(psize)) {
                pagesize = Integer.parseInt(psize);
            }
            if (StringUtils.isNotBlank(pno)) {
                pageno = Integer.parseInt(pno);
            }
            PageResult pr = couponService.queryCanCoupon(WebSession.getWbUser(session).getUserid(), ordermoney, UserService.UserSourceEnum.PC.ordinal(), pagesize, pageno);
            List<Map> list = pr.getList();
            List<JdataBean> dlist = new ArrayList<JdataBean>();
            for (Map bean : list) {
                JdataBean data = new JdataBean();
                data.put("id", WebUtils.aesEncode(bean.get("id").toString()));//id加密
                data.put("name", bean.get("name"));
                data.put("offer_money", bean.get("offer_money"));
                data.put("min_money", bean.get("min_money"));
                data.put("startdate", bean.get("startdate") == null ? "" : bean.get("startdate").toString());
                data.put("enddate", bean.get("enddate") == null ? "" : bean.get("enddate").toString());
                dlist.add(data);
            }
            JdataBean data = new JdataBean();
            data.put("list", dlist);
            data.put("pagecount", pr.getPageCount());
            json.putData(data);
            WebUtils.responseWrite(response, json.toString());
        } catch (Exception e) {
            WebUtils.responseWrite(response, json.toErrorString(this.getClass(), e));
        }
    }

    @RequestMapping("/num")
    @ResponseBody
    public String getNum(HttpSession session) {
        int num = 0;
        if (WebSession.checkLoginStatus(session)) {
            num = couponService.queryCoupon(WebSession.getWbUser(session).getUserid(), 1, UserService.UserSourceEnum.PC.ordinal(), 1, 1).getPageCount();
        }
        JsonReturn json = new JsonReturn();
        json.putData(num);
        return json.toString();
    }
}
